import * as React from 'react';
import { Props, State } from '../type';
import styles from './index.module.less';
import _ from 'lodash';
import { GenerateUUID, GenerateUUID32 } from '@/utils';
import { MatterItem, StandardItem } from '@/pages/official-doc/interface';
import DocMatter from '@/pages/official-doc/components/doc-content/matter';
import ContentCard from '@/pages/official-doc/components/matter-card';
import { FormContentType } from '@/pages/official-doc/components/doc-content/interface.d';
import { DetailMatterCard } from '@/pages/official-doc/components/detail-matter-card';

export class OfficialMatter extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  preValue: undefined;
  provideItems: any;
  preProvideItems: any;

  constructor(props: Props) {
    super(props);
    this.preValue = undefined;
    this.preProvideItems = undefined;
    this.state = {
      ids: [],
      values: [],
      uuid: GenerateUUID32(),
      matterAddList: [], // 事项列表
      target: null, // 当前操作的事项
      showMatterModal: false
    };
  }

  componentDidUpdate(prevProps) {
    this.setDefaultValue(prevProps);
  }

  setDefaultValue = (prevProps) => {
    const prevList = prevProps.formValues?.matterAddList;
    const list = this.props.formValues?.matterAddList;
    if (!prevList && list) {
      console.log(list);
      this.setState({
        matterAddList: list
      });
      // this.props.form.setFieldsValue()
    }
  }

  // 通过路由信息获取是否在修改草稿/重新提交 页面
  isResubmit = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('resubmit?') > -1;
    return isEmitMode;
  };

  // 通过路由信息获取是否在详情 页面
  isDetail = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('/declare/detail?') > -1;
    return isEmitMode;
  };

  getSearchName = (name) => {
    const locationStr = location.hash?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return obj?.[name] || '';
  }

  handleUpdateValues = () => {
    const values = this.props.form?.getFieldValue(this.props.code);
    if (!_.isArray(values)) return;
    // 给每一项设置唯一的ID
    values.forEach((item: any) => {
      const id = GenerateUUID();
      if (!item.id) {
        item.id = id;
      }
    });
    const ids = values.map((item: any) => item.id);
    this.setState({
      values,
      ids
    });
  };

  goNextForm = () => {
    // this.saveData();
    const { matterAddList } = this.state;
    let newMatterAddList = [...matterAddList];
    if (!newMatterAddList?.length) {
      newMatterAddList = [];
    }
    // 事项列表中先新增一项，事项页面点击确认添加后更新这一项的内容，事项页面点击返回时需要排除这一项
    newMatterAddList.push({
      id: GenerateUUID(),
      standardAddList: [] as StandardItem[],
      sort: newMatterAddList.length + 1
    } as MatterItem);
    this.setState({
      matterAddList: newMatterAddList,
      target: newMatterAddList[newMatterAddList.length - 1],
      showMatterModal: true
    });
  };

  // 点击确认或返回的回调
  handleMatterChange = (data: MatterItem, type?: 'back') => {
    const newMatterAddList: MatterItem[] = [];
    const { matterAddList } = this.state;
    matterAddList?.forEach((item: MatterItem) => {
      if (item.id === data.id) {
        if (type === 'back') {
          if (!item.matterName) {
            // 不存在事项名称，说明是新添加的数据，不存入数组（这种判断是否为新添加数据的方式有点坑）
            return;
          }
          return newMatterAddList.push(item);
        }
        return newMatterAddList.push({ ...item, ...data });
      }
      return newMatterAddList.push(item);
    });
    this.setState({
      matterAddList: newMatterAddList,
      showMatterModal: false
    }, this.setFormData);
  };

  setFormData = () => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue && setFieldsValue({
      matterAddList: this.state.matterAddList
    });
    setTimeout(() => {
      console.log('getFieldsValue', this.props.form.getFieldsValue());
    });
  }

  handleMatterDelete = (id: string) => {
    const { matterAddList } = this.state;
    const newMatterAddList = matterAddList?.filter((item: MatterItem) => {
      if (id === item.id) {
        return false;
      }
      return true;
    });
    this.setState({
      matterAddList: newMatterAddList
    }, this.setFormData);
  };

  handleMatterClick = (data: any) => {
    const { matterAddList } = this.state;
    const newMatterAddList = JSON.parse(JSON.stringify(matterAddList));
    let activeTarget;
    newMatterAddList?.forEach((item: MatterItem) => {
      if (item.id === data.id) {
        activeTarget = item;
      }
    });
    this.setState({
      matterAddList: newMatterAddList
    });
    if (activeTarget !== undefined) {
      this.setState({
        target: activeTarget,
        showMatterModal: true
      });
    }
  };

  public render() {
    const { renderMode, formValues, code } = this.props;
    const { showMatterModal, target, matterAddList } = this.state;
    const { getFieldProps } = this.props.form;
    // console.log('this.props', this.props);
    return (
      <div
        {...getFieldProps(code, {
          rules: [
            { required: true, message: '请添加事项' }
          ]
        })}
      >
        {
          renderMode === 'edit' ?
            <>
              {
                matterAddList?.map((item: MatterItem, index: number) => (
                  <ContentCard
                    key={index}
                    type={FormContentType.TOTAL}
                    data={item}
                    handleDelete={this.handleMatterDelete}
                    handleClick={this.handleMatterClick}
                  />
                ))
              }
              <div className={styles.addItem} onClick={this.goNextForm}>+ 添加事项明细</div>
              {
                showMatterModal &&
                <div className={styles.modal}>
                  <DocMatter content={target} handleChange={this.handleMatterChange} />
                </div>
              }
            </>
            :
            <DetailMatterCard list={formValues?.matterAddList || []} />
        }
      </div>
    );
  }
}
